<template>
<!--  @ok="handleSubmit"-->
  <div>
    <BasicModal
      v-bind="$attrs"
      @register="register"
      showFooter
      :title="getTitle"
      width="50%"
      :showOkBtn="false"

    >
      <!--    <BasicForm @register="registerForm"> </BasicForm>-->
      <!--    :label-col="labelCol"-->
      <!--    :wrapper-col="wrapperCol"-->
      <Form
        :model="formData"
        label-align="right"
        ref="formRef"
      >
        <FormItem
          name="orderNo"
          label="入库单号"
        >
          <Input
            placeholder="请输入入库单号"
            v-model:value="formData.orderNo"
          ></Input>
        </FormItem>
        <FormItem
          name="excel"
          label="excel"
        >
          <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD">
            <a-button class="m-3" :loading="loading"> 导入Excel </a-button>
          </ImpExcel>
        </FormItem>
      </Form>
    </BasicModal>

    <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
      <p v-for="(item, index) in msgList">第{{ item.index }}行 {{ item.message }}</p>
    </Modal>
  </div>
</template>
<script lang="ts" setup>
import {ref, computed, unref} from 'vue';
import {BasicForm, useForm} from '@/components/Form';
import {formSchema} from './role.data';
import {BasicModal, useModalInner} from '@/components/Modal';
import { aoaToSheetXlsx, ImpExcel } from '@/components/Excel';

import {BasicTree, TreeItem} from '@/components/Tree';
import { getNoApi} from '@/api/sys/wmProduct';
import { Modal, } from 'ant-design-vue';

import {
  Form,
  FormItem,
  Input,
  Divider
} from 'ant-design-vue';
import {columns, orderColumns, searchFormSchema} from './role.data';
import {useMessage} from '@/hooks/web/useMessage';
import {useRefs} from '@vben/hooks';
import util from "@/utils/util";
import {inStorageApi} from "@/api/sys/wmStorage";

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);
const {refs, setRefs} = useRefs();

const {createMessage} = useMessage();

const formSchemaList = ref(formSchema)
const formData = ref({});
const labelCol = ref({span: 10});
const wrapperCol = ref({span: 13});
const formRef = ref();

const loading=ref(false);

const id = ref('');
const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 90,
  baseColProps: {span: 24},
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [register, {setModalProps, closeModal}] = useModalInner(async (data) => {
  //打开弹层后的回调
  setModalProps({confirmLoading: false});

  isUpdate.value = data?.isUpdate;
  formData.value={orderNo:"",list:[]}
  id.value = '';
  if (unref(isUpdate)) {
    // console.log("---data.record:",data.record)
    id.value = data.record.id;

  } else {
    getNoApi({type: "in_store"}).then((res) => {
      //console.log(res)
      if (res.code == 200) {
        formData.value.orderNo = res.data;
      }
    });

  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增入库信息' : '编辑入库信息'));


let arrHeader=[];
function getHeadArr() {
  let arr = [];
  arrHeader.forEach((r) => {
    arr.push(r.value);
  });
  return arr;
}

function changeSubmitArr(results) {
  let data = {
    list: [],
  };
  let list = [];
  // console.log("--results:",results)
  results.forEach((r) => {
    let json = {};
    for (let key in r) {
      columns.forEach((e) => {
        if (e.excel_title == key) {
          let value=r[key];
          if(value){
            try{
              value=value+"".split(" ").join("");
            }catch (e){
              console.log(e)
            }
          }
          json[e.field] = value;
        }
      });
    }
    data.list.push(json);
  });
  return data;
}

const msgList=ref([]);
const visible=ref(false);

function excelSuccessFn(list) {
  let results = list[0].results;
  // console.log(results);
  //去除第一行文字提示 shift 删除前两行
  results.shift();

  let data = changeSubmitArr(results);
  // console.log(data);

  formData.value.list=data.list;
 // console.log("----formData.value::",formData.value);
  // return;
  loading.value = true;
  inStorageApi(formData.value)
    .then((res) => {
      loading.value = false;

      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          let msg="";
          for(let i=0;i<res.data.length;i++){
            let row= res.data[i];
            msg+=`第${row.index}行 ${row.message}\n`
          }
          msgList.value = res.data;
          visible.value = true;
        } else {
          createMessage.success('导入成功!');
          closeFn();
        }
      } else {
        loading.value = false;

        createMessage.error(res.message);
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}

function closeFn() {
  closeModal()
  emit("success");

}

function handleOk() {
  visible.value = false;
}


</script>

<style lang="less">

.m_w_100 {
  width: 90%;

  .ant-col-6 {
    flex: 0 0 10%;
    max-width: 10%;
  }
}

.ant-form {
  .ant-form-item {
    margin-bottom: 10px;
  }
}
</style>
